/**
* All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
*
* FileBlockRecordService
* 文件分块
*
* 修改纪录
* 2020-08-15 版本：1.0 donghang 创建。
* @version 版本：1.0
* @author 作者：donghang
* 创建日期：2020-08-15
*/
package com.topscomm.meet.service.impl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.topscomm.basic.exception.ServiceException;
import com.topscomm.meet.pojo.FileBlockRecordEntity;
import com.topscomm.meet.service.IFileBlockRecordService;
import com.topscomm.meet.service.impl.auto.FileBlockRecordServiceAuto;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;

import lombok.extern.slf4j.Slf4j;

@Service(value = "fileBlockRecordService")
@Scope(value = "singleton")
@Slf4j
public class FileBlockRecordService extends FileBlockRecordServiceAuto implements IFileBlockRecordService {
	/**
	 * 音视频存储路径
	 */
	@Value("${file.audio.root.path}")
	private String uploadFolder;

	/**
	 * 文件块上传
	 *
	 * @description:
	 * @param
	 * @param blockEntity
	 * @author: donghang
	 * @date: 2020年8月17日上午9:23:35
	 * @modify:
	 */
	@Transactional(rollbackFor = Exception.class)
	public void uploadFileBlock(byte[] fileBytes, Map<String, Object> dataMap) {
		try {
			// 数据库保存文件块，首先判断该文件是否已经上传
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" identifier='{0}' and blocknum='{1}' and sourceid='{2}' and sourcetype='{3}'",
					ConvertUtil.convertToString(dataMap.get("identifier")),
					ConvertUtil.convertToString(dataMap.get("blocknum")),
					ConvertUtil.convertToLong(dataMap.get("sourceid")),
					ConvertUtil.convertToString(dataMap.get("sourcetype")));
			// 不存在的文件块，则插入
			if (this.queryMapByWhere(sql.toString()).size() == 0) {
				// 文件夹路径
				StringBuilder fileDirPath = new StringBuilder();
				fileDirPath.append(uploadFolder).append("/")
						.append(ConvertUtil.convertToString(dataMap.get("identifier")) + "-"
								+ ConvertUtil.convertToString(dataMap.get("sourceid"))
								+ ConvertUtil.convertToString(dataMap.get("sourcetype")))
						.append("/block");
				// 判断uploadFolder/identifier 路径是否存在，不存在则创建
				if (!Files.isWritable(Paths.get(fileDirPath.toString()))) {
					Files.createDirectories(Paths.get(fileDirPath.toString()));
				}
				// 文件写入
				String blockFileName = ConvertUtil.convertToString(dataMap.get("filename"));
				int dotIndex = blockFileName.lastIndexOf(".");
				if (dotIndex == -1) {
					dotIndex = blockFileName.length();
				}
				String suffix = blockFileName.substring(dotIndex);
				blockFileName = blockFileName.substring(0, dotIndex);
				String filePath = fileDirPath.append("/")
						.append(blockFileName + "block-" + ConvertUtil.convertToString(dataMap.get("blocknum")))
						.append(suffix).toString();
				// 删除原块文件
				Path path = Paths.get(filePath);
				if (Files.exists(path)) {
					path = Paths.get(fileDirPath.append("/")
							.append(blockFileName + "block-" + ConvertUtil.convertToString(dataMap.get("blocknum")))
							.append(suffix).toString());
				}
				// Files.deleteIfExists(path);
				log.info("文件写入块开始:" + ConvertUtil.convertToString(dataMap.get("identifier")) + "-"
						+ ConvertUtil.convertToString(dataMap.get("sourceid"))
						+ ConvertUtil.convertToString(dataMap.get("sourcetype"))
						+ ConvertUtil.convertToString(dataMap.get("blocknum")));
				Files.write(path, fileBytes);
				log.info("文件写入块结束:" + ConvertUtil.convertToString(dataMap.get("identifier")) + "-"
						+ ConvertUtil.convertToString(dataMap.get("sourceid"))
						+ ConvertUtil.convertToString(dataMap.get("sourcetype"))
						+ ConvertUtil.convertToString(dataMap.get("blocknum")));
				FileBlockRecordEntity fileBlockRecordEntity = new FileBlockRecordEntity();
				fileBlockRecordEntity = (FileBlockRecordEntity) fileBlockRecordEntity.convertFromMap(dataMap);
				this.insert(fileBlockRecordEntity);
				log.info("数据库插入块结束:" + ConvertUtil.convertToString(dataMap.get("identifier")) + "-"
						+ ConvertUtil.convertToString(dataMap.get("sourceid"))
						+ ConvertUtil.convertToString(dataMap.get("sourcetype"))
						+ ConvertUtil.convertToString(dataMap.get("blocknum")));
			}
		} catch (IOException e) {
			log.error("接收块异常:" + ConvertUtil.convertToString(dataMap.get("identifier")) + "-"
					+ ConvertUtil.convertToString(dataMap.get("sourceid"))
					+ ConvertUtil.convertToString(dataMap.get("sourcetype"))
					+ ConvertUtil.convertToString(dataMap.get("blocknum")) + e.getMessage());
			throw new ServiceException(e.getMessage());
		}

	}
}
